package com.semidata.trp.decision.response;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Set;

import com.semidata.rtd.core.json.JsonArray;
import com.semidata.rtd.core.json.JsonObject;
import com.semidata.rtd.core.log.Logger;
import com.semidata.rtd.engine.job.Job;
import com.semidata.rtd.engine.job.SyncTask;
import com.semidata.trp.decision.business.Material;
import com.semidata.trp.decision.business.Strategy;
import com.semidata.trp.decision.config.Config;
import com.semidata.trp.decision.job.DecisionJob;
import com.semidata.trp.decision.job.DecisionJobContext;
import com.semidata.trp.decision.request.Request;
import com.semidata.trp.decision.select.SelectResult;


public class TaskResponse extends SyncTask {

	private static Config config = Config.getConfig();

	public TaskResponse(Job job, long timeout) {
		super(job, timeout);
	}

	@Override
	public void run() {
		DecisionJob job = (DecisionJob)getJob();
		DecisionJobContext context = job.getJobContext();
		SelectResult result = context.getSelectResult();

		Request request = context.getRequest();
		StringBuffer businessLog = new StringBuffer();

		if (result != null) {
			Strategy strategy = result.getStrategy();
			int aid = strategy.getOrgId();
			int pid = context.getPosition().getId();
			int rid = context.getResource().getId();
			int sid = strategy.getId();
			int mediaType = context.getPosition().getMediaType();
			String uid = URLEncoder.encode(request.getUserId());
			String ip = request.getIp();
			double price = context.getPrice();
			int isDefault = strategy.getPriority() < 0 ? 1 : 0;
			String keyword1 = request.getKeyword1();
			String keyword2 = request.getKeyword2();
			String keyword3 = request.getKeyword3();
			boolean noRequestKeyword = (keyword1 == null && keyword2 == null && keyword3 == null);
			StringBuffer keyQuery = new StringBuffer();
			if (!noRequestKeyword) {
				if (keyword1 != null) {
					keyQuery.append("&k1=")
					.append(keyword1).
					append("&k2=");
					if (keyword2 != null)
						keyQuery.append(keyword2);
					keyQuery.append("&k3=");
					if (keyword3 != null)
						keyQuery.append(keyword3);
				}
			}
			List<Material> materials = result.getMaterial();
			for (Material material : materials) {
				JsonObject obj = new JsonObject();
				int mid = material.getId();
				long time = request.getTimestamp();
				String landingPage = strategy.getLandingPage() != null
						&& !strategy.getLandingPage().isEmpty() ? strategy
						.getLandingPage() : material.getLandingPage();
				if (landingPage == null)
					continue;
				landingPage = URLDecoder.decode(landingPage);
				if (!landingPage.startsWith("http://")
						&& !landingPage.startsWith("https://"))
					landingPage = "http://" + landingPage;
				String src = material.getUrl();
				if (src == null)
					continue;
				if (!src.startsWith("http://") && !src.startsWith("https://"))
					src = "http://" + src;
				StringBuffer sb = new StringBuffer();
				sb.append(config.getUrlMonitorImpression()).append("?a=")
						.append(aid).append("&p=").append(pid).append("&r=")
						.append(rid).append("&s=").append(sid).append("&m=")
						.append(mid).append("&u=").append(uid).append("&t=")
						.append(time).append("&b=").append(price).append("&i=")
						.append(ip).append("&d=").append(isDefault)
						.append("&mt=").append(mediaType).append(keyQuery.toString());
				
				String impUrl = sb.toString();
				sb = new StringBuffer();
				sb.append(config.getUrlMonitorClick()).append("?a=")
						.append(aid).append("&p=").append(pid).append("&r=")
						.append(rid).append("&s=").append(sid).append("&m=")
						.append(mid).append("&u=").append(uid).append("&t=")
						.append(time).append("&b=").append(price).append("&i=")
						.append(ip).append("&d=").append(isDefault)
						.append("&mt=").append(mediaType).append("&o=")
						.append(landingPage).append(keyQuery.toString());

				businessLog.append(' ').append(aid).append('^').append(rid)
						.append('^').append(sid).append('^').append(mid)
						.append('^').append(price).append('^')
						.append(mediaType).append('^').append(landingPage);
				if (keyword1 != null && keyword2 != null && keyword3 != null)
					businessLog.append('^').append(keyword1).append('^').append(keyword2).append('^').append(keyword3);

				String clickUrl = sb.toString();

				obj.putNumber("pid", pid);
				obj.putString("etype", "N");
				if (material.getType().equals(Material.Type.SWF))
					obj.putString("type", "F");
				else
					obj.putString("type", "I");
				obj.putNumber("adw", material.getWidth());
				obj.putNumber("adh", material.getHeight());
				obj.putArray("cm", new JsonArray());
				obj.putString("src", src);

				JsonArray pmArray = new JsonArray();
				pmArray.add(impUrl);
				JsonObject pmObj = new JsonObject();
				pmObj.putArray("0", pmArray);
				obj.putObject("pm", pmObj);

				obj.putString("ldp", clickUrl);
				context.getResponse().add(obj);
			}
		}

		context.setBusinessLog(businessLog.toString());
	}

}
